<template>
  <u-picker :show="cityShow" ref="uPicker" :columns="cityList" @confirm="confirm" @change="changeHandler" @cancel="cancel"></u-picker>
</template>

<script>
import cityData from "@/utils/city.js";
export default {
  props: {
    cityShow: {
      type: Boolean,
      default: false
    },
    format: {
      type: Array,
      default: () => ['province', 'city', 'district']
    }
  },
  computed: {
    formatList() {
      let format = []
      const formatMap = {
        province: this.cityLevel1,
        city: this.cityLevel2[0],
        district: this.cityLevel3[0][0]
      }

      this.format.forEach(item => {
        format.push(formatMap[item])
      })
      return format
    }
  },
  data() {
    return {
      cityList: [], // 城市列表
      cityLevel1: [],
      cityLevel2: [],
      cityLevel3: [],
    };
  },
  created() {
    this.initCityData();
  },
  methods: {
    initCityData() {
      // 遍历城市js
      cityData.forEach((item1, index1) => {
        let temp2 = [];
        this.cityLevel1.push(item1.provinceName);

        let temp4 = [];
        let temp3 = [];
        // 遍历市
        item1.cities.forEach((item2, index2) => {
          temp2.push(item2.cityName);
          // 遍历区
          item2.counties.forEach((item3, index3) => {
            temp3.push(item3.countyName);
          });
          temp4[index2] = temp3;
          temp3 = [];
        });
        this.cityLevel3[index1] = temp4;

        this.cityLevel2[index1] = temp2;
      });
      // 选择器默认城市
      this.cityList.push(...this.formatList);
    },
    // 选中时执行
    changeHandler(e) {
      const {
        columnIndex,
        index,
        indexs,
        value,
        values,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs.uPicker,
      } = e;
      if (columnIndex === 0 && this.format.includes('city')) {
        // 选择第一列数据时
        // 设置第二列关联数据
        picker.setColumnValues(1, this.cityLevel2[index]);
        if (this.format.includes('district')) {
          // 设置第三列关联数据
          picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
        }
      } else if (columnIndex === 1 && this.format.includes('district')) {
        // 选择第二列数据时
        // 设置第三列关联数据
        picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
      }
    },
    // 单击确认按钮时执行
    confirm(e) {
      // 输出数组 [省, 市, 区]
      this.$emit('confirm', e);
    },
    cancel() {
      this.$emit('cancel');
    }
  }
};
</script>

<style scoped>

</style>
